<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="签名名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入签名名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['work:signature:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['work:signature:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['work:signature:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['work:signature:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="signatureList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="签名编号" align="center" prop="signatureId"/>
      <el-table-column label="部门名称" align="center" prop="deptName"/>
      <el-table-column label="创建人" align="center" prop="userName"/>
      <el-table-column label="签名名称" align="center" prop="name"/>
      <el-table-column label="签名图片" align="center" prop="imgUrl" width="100">
        <template slot-scope="scope">
          <image-preview v-if="scope.row.imgUrl" :src="scope.row.imgUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['work:signature:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['work:signature:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改签名对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="签名名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入签名名称" maxlength="50" show-word-limit/>
        </el-form-item>
        <el-form-item label="签名图片" prop="imgUrl">
          <!-- 用户用来预览签字图片的地方 -->
          <el-button v-if="form.imgUrl === null || form.imgUrl=== ''" type="primary" @click="enterSignature">
            录入签名
          </el-button>
          <image-upload v-else v-model="form.imgUrl" :isShowTip="false" :limit="1"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" maxlength="255" show-word-limit/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisible" append-to-body title="录入签名" width="500px">
      <!-- 使用这个签名组件 -->
      <vue-esign
        ref="esign"
        :height="300"
        :isCrop="isCrop"
        :lineColor="lineColor"
        :lineWidth="lineWidth"
        :width="500"
        class="mySign"
      />
      <div style="margin-top: 10px">
        <div class="demonstration">
          线条粗细：
        </div>
        <el-slider
          v-model="lineWidth"
          :max="20"
          :min="1"
          show-input>
        </el-slider>

        <div class="demonstration">
          线条颜色：
        </div>
        <el-color-picker v-model="lineColor"></el-color-picker>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleGenerate">生成录入签名</el-button>
        <el-button @click="handleReset">清空画板</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {addSignature, delSignature, getSignature, listSignature, updateSignature} from "@/api/work/signature";
import VueEsign from 'vue-esign'
import axios from 'axios'
import {getToken} from "@/utils/auth";

export default {
  name: "Signature",
  components: {
    VueEsign
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 签名表格数据
      signatureList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 备注时间范围
      daterangeCreateTime: [],
      // 备注时间范围
      daterangeUpdateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        createTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          {required: true, message: "签名名称不能为空", trigger: "blur"}
        ],
        imgUrl: [
          {required: true, message: '签名图片路径不能为空', trigger: 'blur'}
        ]
      },

      uploadImgUrl: process.env.VUE_APP_BASE_API + '/common/upload', // 上传的图片服务器地址

      dialogVisible: false, // 弹框是否开启
      lineWidth: 4, // 画笔的线条粗细
      lineColor: '#000000', // 画笔的颜色
      isCrop: false, // 是否裁剪，在画布设定尺寸基础上裁掉四周空白部分
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 录入签名
    enterSignature() {
      this.dialogVisible = true

      this.$nextTick(() => {
        this.handleReset()
      })
    },
    // 清空画板
    handleReset() {
      this.$refs.esign.reset()
    },
    base64ImgtoFile(dataurl, filename = 'file') {
      let arr = dataurl.split(',')
      let mime = arr[0].match(/:(.*?);/)[1]
      let suffix = mime.split('/')[1]
      let bstr = atob(arr[1])
      let n = bstr.length
      let u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], `${filename}.${suffix}`, {
        type: mime
      })
    },
    // 生成签字图
    handleGenerate() {
      this.$refs.esign
        .generate() // 使用生成器调用把签字的图片转换成为base64图片格式
        .then((res) => {
          const imgFile = this.base64ImgtoFile(res, 'signature')
          let formData = new FormData()
          formData.append('file', imgFile)
          formData.append('width', 90)
          formData.append('height', 36)
          // formData.append("isTransparent", false)
          const loading = this.$loading({
            lock: true,
            text: '正在上传图片，请稍候...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })

          axios.post(this.uploadImgUrl, formData, {
              headers: {  //头部参数
                'content-type': 'application/x-www-form-urlencoded',
                Authorization: 'Bearer ' + getToken()
              }
            }
          ).then((response) => { //请求成功
            this.form.imgUrl = response.data.fileName
            loading.close()
            this.dialogVisible = false
            this.handleReset()
          }).catch((error) => { //请求失败

            })
        })
        .catch((err) => {
          // 画布没有签字时会执行这里提示一下
          this.$message({
            type: 'warning',
            message: '请签名后再生成签名图片'
          })
        })
    },
    /** 查询签名列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      if (null != this.daterangeUpdateTime && '' != this.daterangeUpdateTime) {
        this.queryParams.params["beginUpdateTime"] = this.daterangeUpdateTime[0];
        this.queryParams.params["endUpdateTime"] = this.daterangeUpdateTime[1];
      }
      listSignature(this.queryParams).then(response => {
        this.signatureList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        signatureId: null,
        deptId: null,
        userId: null,
        deptName: null,
        userName: null,
        name: null,
        imgUrl: null,
        remark: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.daterangeUpdateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.signatureId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加签名";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const signatureId = row.signatureId || this.ids
      getSignature(signatureId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改签名";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.signatureId != null) {
            updateSignature(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSignature(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const signatureIds = row.signatureId || this.ids;
      this.$modal.confirm('是否确认删除签名编号为"' + signatureIds + '"的数据项？').then(function () {
        return delSignature(signatureIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('work/signature/export', {
        ...this.queryParams
      }, `signature_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
